<?php
require_once ('utils' . DIRECTORY_SEPARATOR . 'DeCaptcha.php');
require_once ('utils' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'simple_html_dom.php');
require_once ('utils' . DIRECTORY_SEPARATOR . 'HHAbstract.php');

set_time_limit(-1);

class HHSPlaceBids extends HHAbstract {

	const URL = 'http://www.hudhomestore.com/';

	function __construct() {
		parent::__construct();
	}

	function __destruct() {
		parent::__destruct();
	}

	function constructClass() {
		$this -> handleARGV();

		// TODO: remove line below
		/*
		$this -> placeBidOnCase(array(
			'user' => 'LDavis311',
			'pass' => 'Homes#2013',
			'case' => '241-798818',
			'NAID' => 'CTYPRP7574',
			'license' => '647281',
			'bid_amount' => 10000,
			'finance_type' => 0,
			'seller_closing_cost' => 0,
			'broker_commission_cost' => 500,
			'purchaser_type' => 'I',
			'accept_as_backup_offer' => -1,
			'purchaser_id_type' => 1,
			'purchaser_id_number' => '212-23-0242',
			'purchaser_first_name' => 'Christopher',
			'purchaser_last_name' => 'Queen',
			'address' => '4912 55th Ave',
			'city' => 'Hyattsville',
			'state' => 'MD',
			'zip' => '20781',
		));
		*/
	}

	function handleARGV() {
		global $argv;
		if (!isset($argv) || count($argv) <= 1) {
			$this -> getNewBids();

		}
		else {
			array_shift($argv);
			foreach ($argv as $value) {
				$keyArray = split("=", $value);
				$key = $keyArray[0];
				$keyValue = $keyArray[1];
				switch ($key) {
					case "bidId" :
						$bidId = $keyValue;
						if (isset($state)) {
							$this -> placeBid($bidId);
						}
						break;
					default :
						echo("Incorrect argument usage. Please use one of the following:\n");
				}
			}
		}
	}

	private function getNewBids() {
		// Convert the current time into a UTC timestamp
		$now = time();
				
		// Get the new bids that havent been scheduled and the time has passed that have no bid_results and have no confirmation number
		$query = 'Select ub.id as bidId
			from user_bids as ub 
			LEFT JOIN bid_results as brs ON brs.`case` = ub.`case`
			WHERE
			brs.case is null
			AND ub.confirmation_number is null
			AND ub.scheduled_submission_time > \''.$now.'\'		
			limit=10';
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		while (($row = $result -> fetch_assoc())) {
			$bidId = $row["bidId"];
			//$cmd = $className . ".php bidId=$bidId";
			//$this -> getCommandLineHelper() -> run_in_background($cmd, $file);
			$this->placeBid($bidId); // TODO: remove when query is right
		}

	}

	private function placeBid($bidId) {
		$query = "SELECT  
			ag.user,
			ag.pass,
			agl.license,
			br.NAID,
			us.first_name AS `purchaser_first_name`,
			us.middle_name AS `purchaser_middle_name`,
			us.last_name AS `purchaser_last_name`,
			adr.address,
			adr.city,
			adr.state,
			adr.zip,
			ub.bid_amount,
			ub.finance_type,
			ub.seller_closing_cost,
			ub.broker_commission_cost,
			ub.purchaser_type,
			ub.accept_as_backup_offer,
			upi.value as `purchaser_id_number`,
			ub.case
			
			from user_bids AS ub 
			LEFT JOIN users as us ON us.id=ub.user_id
			LEFT JOIN user_address as adr ON ub.user_address_id = adr.id AND adr.user_id=us.id
			LEFT JOIN user_purchase_ids as upi ON upi.id= ub.user_purchase_id
			LEFT JOIN agents as ag ON ag.id=ub.agent_id
			LEFT JOIN agent_license as agl ON agl.agent_id=ag.id AND agl.id=ub.license_id
			LEFT JOIN brokers as br ON br.id = ag.broker_id AND br.id = ub.broker_id
			
			WHERE 
			ub.id=" . $bidId;
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		$bidInfo = $result -> fetch_assoc();
		$this -> placeBidOnCase($bidInfo);

	}

	public function placeBidOnCase(array $bidInfo) {
		$validBidInfo = $this -> validBidInfo($bidInfo);
		if ($validBidInfo === true) {
			// Get all the information about the bid to place new bid
			$user = $bidInfo['user'];
			$pass = $bidInfo['pass'];
			$caseNumber = $bidInfo['case'];
			$NAID = $bidInfo['NAID'];
			$RELicense = $bidInfo['license'];

			$startUrl = self::URL . "Listing/PropertyDetails.aspx?caseNumber=" . $caseNumber;
			//echo($this->getUrlAsLink($startUrl).'<br>');
			$hudhomestore = $this -> get_web_page($startUrl);

			$html = str_get_html($hudhomestore . ' ');
			
			//echo('HTML after Property Details <br>'.$html.'<br><br><hr><br><br>');

			if ($html === false) {
				echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($startUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
				return false;
			}
			$pattern = '/https:\/\/www\.hudhomestore\.com\/Listing\/NaidVerification\.aspx\?sLanguage=ENGLISH&caseNumber=(.*?)&/';
			$matches = array();
			preg_match($pattern, $html, $matches);
			$submitUrl = '';

			if (count($matches) > 0 && isset($matches[1])) {
				$encryptedCaseNumber = $matches[1];
				$submitUrl = 'https://www.hudhomestore.com/pages/NaidVerification.aspx?Page=NaidVerification&PageGroup=Listing&sLanguage=ENGLISH&caseNumber=' . $encryptedCaseNumber;

				//echo('Naid Verification Url: '.$this->getUrlAsLink($submitUrl).'<br>');
				$hudhomestoreSubmit = $this -> get_web_page($submitUrl);

				$html = str_get_html($hudhomestoreSubmit . ' ');

				if ($html === false) {
					echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($submitUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
					return false;
				}
				
				//echo('HTML after NAID Verification<br>'.$html.'<br><br><hr><br><br>');

				$hiddenInputData = array();
				foreach ($html->find('input[type=hidden]') as $hiddenInput) {
					if ($hiddenInput -> name != 'recaptcha_response_field') {
						$hiddenInputData[$hiddenInput -> name] = $hiddenInput -> value;

					}
				}

				//echo('Hidden Input Fields<br>');
				//var_dump($hiddenInputData);
				//echo('<br><br>');

				//die('<pre>'.$html.'</pre>');

				$js = null;
				$jsFound = array();
				foreach ($html->find('script') as $script) {
					$src = $script -> src;
					$jsFound[] = $src;
					if (stripos($src, 'www.google.com/recaptcha/api/challenge') !== false) {
						$js = $src;
						break;
					}
				}

				if (!isset($js)) {
					echo("<b><font color='red'>Could not find JS needed to get captcha information.</font></b>");
					echo("JS Found:<br>");
					var_dump($jsFound);
					echo("<br>");
					
					return false;
				}

				$googleRecaptchaAPiChallenge = $this -> get_web_page($js);
				$html = str_get_html($googleRecaptchaAPiChallenge . ' ');

				$pattern = '/challenge : \'(.*?)\'/';
				$matches = array();
				preg_match($pattern, $html, $matches);

				if (count($matches) > 0 && isset($matches[1])) {
					$captchaChallengeField = $matches[1];
					//$captchaChallengeField ='03AHJ_Vuuv09w0vYtZTIjEW_gP3dSqhy8B7pjT2z24w6PmP_vWCzr1a0LERB1_ncj-yB2JUi8XVHTcOW_KTynHWT6Wd1zGAaM_JHC6y9N1L37ivGQ0C5rbPTNLMKbwGaCxd3ds4uo09EGJ7y4FJWrpn9qp9QAgEj3U0Tz3L44lkkwRWRlp21LqH6rEzMOCjHj_JQ9KZdsgAYooqIvPaHozbjvZI8NAZ5I2mg';
					$captchaSrc = 'https://www.google.com/recaptcha/api/image?c=' . $captchaChallengeField;
				}

				//echo('Captcha Src:'.$this->getUrlAsLink($captchaSrc).'<br>');
				//echo('Captcha Feild:'.$captchaChallengeField.'<br>');

				$deCaptcha = new DeCaptcha(decaptchauser, decaptchapass);
				$captchaText = $deCaptcha -> getCatchaText($captchaSrc);
				//$captchaText = 'sylvius dshedeo';

				//echo("Solved Captcha: ".$captchaText.'<br>');

				$postData = array(
					'btnSubmit' => 'Verify NAID',
					'ddNaidType' => 'SellingBroker',
					'recaptcha_challenge_field' => $captchaChallengeField,
					'recaptcha_response_field' => $captchaText,
					'txtNAID' => $NAID,
					'txtRealEstateLicense' => $RELicense,
				);

				// Include the hidden input data
				foreach ($hiddenInputData as $index => $value) {
					$postData[$index] = $value;
				}

				$postDataAsString = http_build_query($postData);

				$additionalCurlOptions = array(
					CURLOPT_POST => 1,
					CURLOPT_POSTFIELDS => $postDataAsString,
				);

				$naidVerificationUrl = 'https://www.hudhomestore.com/pages/NaidVerification.aspx?Page=NaidVerification&PageGroup=Listing&sLanguage=ENGLISH&caseNumber=' . urldecode($encryptedCaseNumber) . "&Page=NaidVerification&PageGroup=Listing&iHeight=770";
				//$naidVerificationUrl = 'https://www.hudhomestore.com/pages/NaidVerification.aspx?Page=NaidVerification&PageGroup=Listing&sLanguage=ENGLISH&caseNumber=MjQxLTcxODg2MA%3d%3d&&iHeight=770';

				//echo("Naid Verification Url: ".$this->getUrlAsLink($naidVerificationUrl).'<br>');

				$hudhomestoreNaidVerification = $this -> get_web_page($naidVerificationUrl, false, $additionalCurlOptions);

				// Then redirect to Bid Page
				//$bidUrl = 'https://www.hudhomestore.com/Listing/BidSubmission.aspx?sLanguage=ENGLISH';
				$bidUrl = 'https://www.hudhomestore.com/pages/BidSubmission.aspx?Page=BidSubmission&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';
				$bidHtml = $this -> get_web_page($bidUrl, false, array(CURLOPT_POST => false, ));

				$html = str_get_html($bidHtml . ' ');

				if ($html === false) {
					echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($naidVerificationUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
					return false;
				}

				//echo($html);

				// Submit the Bid
				$this -> submitBidStep($html,$bidInfo);

				// Confirm Bid submission

			}
			else {
				die('Could not find the sumbit url for case: ' . $caseNumber);
			}

		}
		else {
			echo(implode("\n\r<br>", $validBidInfo));
		}
	}

	private function submitBidStep($html, array $bidInfo) {

		$bAmount = $bidInfo['bid_amount'];
		$financeType = $bidInfo['finance_type'];
		$sClosingCost = $bidInfo['seller_closing_cost'];
		$bCommissionCost = $bidInfo['broker_commission_cost'];
		$pType = $bidInfo['purchaser_type'];
		$acceptBackUpOffer = $bidInfo['accept_as_backup_offer'];
		//$pIdType = $bidInfo['purchaser_id_type'];
		$pIdNum = $bidInfo['purchaser_id_number'];
		$pCompanyName = $bidInfo['purchaser_company_name'];
		$pFirstName = $bidInfo['purchaser_first_name'];
		$pMiddleName = $bidInfo['purchaser_middle_name'];
		$pLastName = $bidInfo['purchaser_last_name'];
		$pAddress = $bidInfo['address'];
		$pCity = $bidInfo['city'];
		$pState = $bidInfo['state'];
		$pZip = $bidInfo['zip'];
		$pEmail = $bidInfo['email'];
	
		$enableSecondPurchaser = 'off';

		$hiddenInputData = array();
		foreach ($html->find('input[type=hidden]') as $hiddenInput) {
			$hiddenInputData[$hiddenInput -> name] = $hiddenInput -> value;
		}
		
			
		$agentInputData = array();
		foreach ($html->find("input[name^=txtSellingAgent]") as $agentInput) {
				$agentInputData[$agentInput -> name] = $agentInput -> value;
		}
		
		$listingBrokerComission = $bAmount*.03;
		$bCommissionCost = min(array($listingBrokerComission,$bCommissionCost));
		$netBidAmount = $bAmount - ($listingBrokerComission+$sClosingCost+$bCommissionCost);

		$postData = array(
			'btnContinue' => 'Continue',
			'chkEnableSecondaryPurchaser' => $enableSecondPurchaser,
			
			'hdnBidAmount' =>  number_format($bAmount,2),
			'txtBidAmount' => number_format($bAmount,2),
			'txtClosingCosts' => number_format($sClosingCost,2),
			'txtListingBrokerCommission' => number_format($listingBrokerComission,2),
			'txtSellingBrokerCommission' => number_format($bCommissionCost,2),
			'txtNetBidAmount' => number_format($netBidAmount,2),
			'hdnDollarHome' => '',
			'rbBackupOffer' => $acceptBackUpOffer,
			'rbFinancingType' => $financeType,
			'rbOwnerType' => $pType,
			
			'rbPrimaryPurchaserType' => $pType,
			'txtPrimaryPurchaserAddress' => $pAddress,
			'txtPrimaryPurchaserCity' => $pCity,
			'ddPrimaryPurchaserState' => $pState,
			'txtPrimaryPurchaserZipCode' => $pZip,
			'txtPrimaryPurchaserCompanyName' => $pCompanyName,
			'txtPrimaryPurchaserEmail' => $pEmail,
			'txtPrimaryPurchaserFirstName' => $pFirstName,
			'txtPrimaryPurchaserMiddleName' => $pMiddleName,
			'txtPrimaryPurchaserLastName' => $pLastName,
			'txtPrimaryPurchaserSSNEIN' => $pIdNum,
			'txtPrimaryPurchaserSSNEINConfirm' => $pIdNum,
			
		);
		
		if (isset($bidInfo['purchaser_id_type2'])) {
			$enableSecondPurchaser = 'on';
			//$pIdType2 = $bidInfo['purchaser_id_type2'];
			$pIdNum2 = $bidInfo['purchaser_id_number2'];
			$pCompanyName2 = $bidInfo['purchaser_company_name2'];
			$pFirstName2 = $bidInfo['purchaser_first_name2'];
			$pMiddleName2 = $bidInfo['purchaser_middle_name2'];
			$pLastName2 = $bidInfo['purchaser_last_name2'];
			$pAddress2 = $bidInfo['address2'];
			$pCity2 = $bidInfo['city2'];
			$pState2 = $bidInfo['state2'];
			$pZip2 = $bidInfo['zip2'];
			$pEmail2 = $bidInfo['email2'];
		
			$postData['rbSecondaryPurchaserType'] = $pType;
			$postData['txtSecondaryPurchaserAddress'] = $pAddress2;
			$postData['txtSecondaryPurchaserCity'] = $pCity2;
			$postData['ddSecondaryPurchaserState'] = $pState2;
			$postData['txtSecondaryPurchaserZipCode'] = $pZip2;
			$postData['txtSecondaryPurchaserCompanyName'] = $pCompanyName2;
			$postData['txtSecondaryPurchaserEmail'] = $pEmail2;
			$postData['txtSecondaryPurchaserFirstName'] = $pFirstName2;
			$postData['txtSecondaryPurchaserMiddleName'] = $pMiddleName2;
			$postData['txtSecondaryPurchaserLastName'] = $pLastName;
			$postData['txtSecondaryPurchaserSSNEIN'] = $pIdNum2;
			$postData['txtSecondaryPurchaserSSNEINConfirm'] = $pIdNum2;
			
			
		}

		// Include the hidden input data
		foreach ($hiddenInputData as $index => $value) {
			if(!isset($postData[$index])){
				$postData[$index] = $value;
			}
		}
		
		// Include the agent data
		foreach ($agentInputData as $index => $value) {
			if(!isset($postData[$index])){
				$postData[$index] = $value;
			}
		}
		
		//echo('Post Data:<br>');
		//var_dump($postData);
		//echo('<br><br>');

		$postDataAsString = http_build_query($postData);

		$additionalCurlOptions = array(
			CURLOPT_POST => 1,
			CURLOPT_POSTFIELDS => $postDataAsString,
		);

		$bidSumbmitUrl = 'https://www.hudhomestore.com/pages/BidSubmission.aspx?Page=BidSubmission&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';

		$hudhomestoreBidConfirmation = $this -> get_web_page($bidSumbmitUrl, false, $additionalCurlOptions);
		
		$html = str_get_html($hudhomestoreBidConfirmation . ' ');
		
		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidSumbmitUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		
		$file1 = realpath ( dirname ( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'utils' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'bidSubmit.html';
		
		$html->save($file1);
		
		
		// Then redirect to Bid Page
		//$bidUrl = 'https://www.hudhomestore.com/Listing/BidSubmission.aspx?sLanguage=ENGLISH';
		$bidUrl = 'https://www.hudhomestore.com/pages/BidSummary.aspx?Page=BidSummary&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';
		$bidHtml = $this -> get_web_page($bidUrl, false, array(CURLOPT_POST => false, ));

		$html = str_get_html($bidHtml . ' ');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		
		$file2 = realpath ( dirname ( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'utils' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'bidSubmit2.html';
		
		$html->save($file2);
		
		//die("<br><br><hr><br><br>".$html);
		
		// Go to the bid acknowledgment page confirms your bid
		$bidAcknowledgeUrl = 'https://www.hudhomestore.com/pages/BidAcknowledgement.aspx?Page=BidAcknowledgement&PageGroup=Listing&sLanguage=ENGLISH&iHeight=0';
		//$bidAcknowledgeUrl = 'https://www.hudhomestore.com/Listing/BidAcknowledgement.aspx?sLanguage=ENGLISH';
		$bidAcknowledgeHtml = $this -> get_web_page($bidAcknowledgeUrl);

		$html = str_get_html($bidAcknowledgeHtml . ' ');

		if ($html === false) {
			echo("<b><font color='red'>Could not process URL: " . $this -> getUrlAsLink($bidAcknowledgeUrl) . "<br>Consider increasing the MAX_FILE_SIZE in simple_html_dom.php or make sure the url actually returns a page.</font></b>");
			return false;
		}
		
		$file3 = realpath ( dirname ( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'utils' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'bidSubmit3.html';
		
		$html->save($file3);
		
		
		// Get the confirmation number
		//lblHeaderBidReceiptConfirmationNumber
		$confirmationNumber = $html->find('span[id=lblHeaderBidReceiptConfirmationNumber]',0)->plainText ;
		$this->updateBidWithConfirmationNumber($bidInfo['bidId'],$confirmationNumber);
		
		
		//die("<br><br><hr><br><br>".$html);
		
		die("Bid Submitted!!!");
		
	}

	private function updateBidWithConfirmationNumber($bidID, $confirmationNumber){
		$query = 'UPDATE bids set confirmation_number=\''.$confirmationNumber.'\' WHERE bidId='.$bidID;
		$result = $this -> runQuery($query, $this -> getDBConnection() -> getDBConnection());
		
	}

	private function validBidInfo(array $bidInfo) {
		$mustBeSet = array(
			'user',
			'pass',
			'case',
			'NAID',
			'license',
			'bid_amount',
			'finance_type',
			'seller_closing_cost',
			'broker_commission_cost',
			'purchaser_type',
			'accept_as_backup_offer',
			//'purchaser_id_type',
			'purchaser_id_number',
			'purchaser_first_name',
			'purchaser_last_name',
			'address',
			'city',
			'state',
			'zip',
		);
		$mustBeANumber = array(
			'bid_amount',
			'seller_closing_cost',
			'broker_commission_cost',
			'zip',
			'zip2',
		);
		$errors = array();

		foreach ($mustBeSet as $index) {
			if (!isset($bidInfo[$index]) || strlen($bidInfo[$index]) == 0) {
				$errors[] = $index . ' Must be set.';
			}
		}

		foreach ($mustBeANumber as $index) {
			if (isset($bidInfo[$index]) && is_nan($bidInfo[$index])) {
				$errors[] = $index . ' Must be a number.';
			}
		}
		return (count($errors) == 0) ? true : $errors;

	}

	function logIntoHomeStores($user, $pass) {

	}

}

$obj = new HHSPlaceBids();
?>